package com.hyc.netty.client;

import com.hyc.message.RpcRequest;
import com.hyc.message.RpcResponse;
import com.hyc.serviceCenter.NacosServiceCenter;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;
import lombok.Getter;

import java.util.concurrent.CompletableFuture;

/**
 * @author 冷环渊
 * @date 2025/6/6 19:03
 * @description NettyRpcClient
 */

public class NettyRpcClient {

    private static final Bootstrap bootStrap;
    private static final NioEventLoopGroup eventLoopGroup;
    @Getter
    private NacosServiceCenter nacosServiceCenter;

    public NettyRpcClient() {
        this.nacosServiceCenter = new NacosServiceCenter();
    }


    static {
        bootStrap = new Bootstrap();
        eventLoopGroup = new NioEventLoopGroup();
        bootStrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new NettyClientInitializer());
    }

    public CompletableFuture<RpcResponse> sendRpcRequest(RpcRequest request) {
        CompletableFuture<RpcResponse> future = new CompletableFuture<>();
        //连接服务器
        ChannelFuture channelFuture = bootStrap.connect(nacosServiceCenter.serviceDiscovery(request.getInterfaceName())).addListener(connectFuture -> {
            if (!connectFuture.isSuccess()) {
                future.completeExceptionally(connectFuture.cause());
            }
        }).syncUninterruptibly();
        Channel channel = channelFuture.channel();
        //future 存储到 channel中
        AttributeKey<CompletableFuture<RpcResponse>> responseKey = AttributeKey.valueOf("rpcResponse" + request.getRequestId());
        channel.attr(responseKey).set(future);
        //发送数据
        channel.writeAndFlush(request);
        return future;
    }
}
